<template>
  <div class="address">
    <div>
      <h2>我的地址</h2>
      <el-divider></el-divider>
    </div>

    <el-dialog :title="current_title" :visible.sync="datasetDialogVisible">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="地区信息">
          <el-cascader
              size="large"
              :options="options"
              v-model="selectedOptions"
              @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" >
          <el-input v-model="form.address" ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-checkbox v-model="form.isDefault">设置默认地址</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 这是地址页面的表格 -->
    <div class="num">
      <el-button class="page-area" type="primary" @click="distable">新建</el-button>
    </div>

    <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%">
      <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
<!--      <el-table-column-->
<!--          align="center"-->
<!--          label="">-->
<!--        <template slot-scope="scope">-->
<!--        {{scope.$index.add(1)}}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
          align="center"
          prop="address"
          label="地区">
      </el-table-column>
      <el-table-column
          align="center"
          prop="detailAdd"
          label="详细地址">
      </el-table-column>
      <el-table-column
          align="center"
          prop="name"
          label="名称"
          width="180">
      </el-table-column>
      <el-table-column
          align="center"
          prop="phone"
          label="电话"
          width="180">
      </el-table-column>
      <el-table-column
          align="center"
          label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-area">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { regionData, codeToText } from "element-china-area-data";
export default {
  components: {},
  props: {},
  data() {
    return {

      current_title: "",
      datasetDialogVisible: false,
      form: {
        id: null,
        name: "",
        address: "",
        phone:'',
        isDefault: false,
      },
      pageSize: 10,
      currentPage: 1,
      total: 0,
      options: regionData,
      selectedOptions: [],
      addtions: {}, //存储地址数据
      num:'0',
      tableData: [],
      userInfo:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):{}

    };
  },
  watch: {},
  computed: {},
  methods: {
    handleCurrentChange (val) {
      this.currentPage = val
      this.getList()
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getList()
    },
    distable() {
      this.current_title = '新建';
      // 这是地区编码
      this.selectedOptions = {};
      this.clearForm();
      this.datasetDialogVisible = true
    },
    // 新建按钮
    onSubmit() {
      let b = this.form.address
      this.request.post('/address',{
        id: this.form.id,
        name: this.form.name,
        address: this.addtions.names,
        phone:this.form.phone,
        isDefault: this.form.isDefault === true ? 1 : 0,
        detailAdd: b,
        fullAdd: this.addtions.names+b,
        uid: this.userInfo.data.id,
        provinceCode: this.selectedOptions[0],
        countyCode: this.selectedOptions[1],
        areaCode: this.selectedOptions[2]
      }).then(res=>{
        if(res.data.code === "200"){
          let msg1 = "恭喜小主，又多了一个牵挂的地方！"
          let msg2 = "更新成功！"
          this.$message.success(this.current_title === '新建' ? msg1 : msg2)
          this.clearForm();
          this.addtions = {}
          this.selectedOptions = []
          this.getList()
          this.datasetDialogVisible = false
        }
      })

    },
    // 取消按钮
    cancel(){
      this.datasetDialogVisible = false
    },
    clearForm() {
      this.form.id = null
      this.form.address = ""
      this.form.name = ""
      this.form.phone = ""
      this.form.isDefault = false;
    },
    // 编辑按钮
    handleEdit(index, row){
      this.current_title = '编辑'
      this.datasetDialogVisible = true
      this.selectedOptions = [row.provinceCode,row.countyCode,row.areaCode]
      this.addtions.names = row.address
      this.form.id = row.id
      this.form.address = row.detailAdd
      this.form.name = row.name
      this.form.phone = row.phone
      this.form.isDefault = row.isDefault === 1;
    },
    // 删除按钮
    handleDelete(index,row){
      this.$confirm('小主！您的操作将永久删除该地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.request.delete('/address/'+row.id).then(res=>{
          if(res.data.code ==="200"){
            this.$message.success("已听从您的指示！为您净化空间啦！")
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '还好还好！可以挽回！已为您取消删除该地址'
        });
      });

    },

    handleChange(value) {
      //我们选择地址后，selectedOptions 会保存对应的区域码，例如北京的区域码为'110000'
      //我们要取出区域码对应的汉字，就需要用CodeToText(区域码)进行输出
      this.addtions.selectedOptions = value;
      var name = "";
      this.selectedOptions.map((item) => (name += codeToText[item]));
      this.addtions.names = name;
    },
    getList() {
      this.request.get("/address/page?uid=" + this.userInfo.data.id +
          '&pageNum=' + this.currentPage +
          '&pageSize=' + this.pageSize).then(res => {
        if (res.data.data.total > 0) {
          this.tableData = res.data.data.records;
          this.num = res.data.data.total;
          this.total = res.data.data.total
        }

      })
    }
  },
  created() {
    if (this.userInfo.data === undefined) {
      this.$router.push("/login");
      this.$message({
        showClose: true,
        type: "warning",
        message: "请进行登录！",
      });
    }
    this.getList()
  },
  mounted() {},
};
</script>
<style scoped>
.el-input {
  width: 60%;
}
.el-cascader {
  width: 30%;
}
.page-area {
  float: right;
  margin-right: 24px;
}
.table-area {
  overflow: auto;
  max-height: calc(100vh - 10px - 20px - 10px - 10px);
  padding: 10px;
  background-color: #ffffff;
  border-radius: 10px;
  margin-bottom: 10px;
}
</style>